<?php

namespace App\Services\OpenGroup;

use App\Models\Group;
use App\Models\GroupCard;
use App\Models\GroupRecord;
use App\Models\User;
use App\Models\Product;
use App\Models\ProductSku;
use Carbon\Carbon;
use App\Models\Address;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Api\V1\Requests\FormRequest;
use Rainsens\Dinglog\Facades\Dinglog;

class JoinGroupRequest extends FormRequest
{ 
	public function rules()
	{
		$addressId =  (int)request('address_id');
		if ($addressId) {
			$this->address = Address::find($addressId);
		}
		return [
			'group_id' => [
				'required',
				'integer',
				'min:1',
				$this->group(),
			],
			'sku_id' => [
				'required',
				'integer',
				'min:1'
			],
			'address_id' => ['required', $this->address()],
			
		];
	}

	public function group()
	{
		return function ($key, $value, $fail) {


			$group  = Group::find($value);
			$user = request()->user();

			if (!$group) {
				return $fail('该团不存在');
			}elseif ($group->is_finished) {
				return $fail('该团已完结');
			} elseif (Carbon::parse($group->group_expired_at)->lt(Carbon::now())) {
				return $fail('该团已过期');
			}



			return true;
		};
	}

	public function address()
	{
		return function ($attribute, $value, $fail) {
			
			if (!$this->address) {
				return $fail('地址不存在');
			}
			return true;
		};
	}

	
	public function getAddress(): Address
	{
		return $this->address;
	}

	public function items()
	{
		$group = Group::find($this->group_id);
		$product = Product::find($group->product_id);

		$skuProduct = ProductSku::find($this->sku_id);
		if(!$product){

			fail('该团没有选择商品!');
		}
		if($product->id != $skuProduct->product_id){

			fail('该商品不是当前开团商品!');
		}


		$item['items'] = [
			'sku_id'=>$this->sku_id,
			'amount'=> 1,
			'group_id'=>$this->group_id,
		];
		return $item;


	}

}
